import java.util.Collections;
import java.util.concurrent.CountDownLatch;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2023-08-03
 * Time: 18:01
 */

class MyThread extends Thread{
    private final int num;
    private final CountDownLatch latch;
    public MyThread(int num, CountDownLatch latch){
        this.num = num;
        this.latch = latch;
    }


    @Override
    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            System.out.println("Thread: " + num + "执行完了! " );
            // 该线程执行完毕, 计数器 - 1
            latch.countDown();
        }
    }
}

public class Main {
    public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(20);
        for (int i = 0; i < 20; i++) {
            Thread thread = new MyThread(i, latch);
            thread.start();
        }
        try {
            // 等待所有线程执行完毕
            latch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("ok");
    }
}
